<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Store;
use App\Models\PickupPointApplication;
use App\Models\Address;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Layout\Column;

class PickupPointController extends Controller
{
    /**
     * 自提点清单
     *
     * @param Content $content
     * @param Request $request
     * @return Content
     */
    public function index(Content $content, Request $request)
    {
        return $content
            ->title('自提点清单')
            ->description('管理所有通过审核的自提点信息')
            ->body($this->renderPickupPointList($request));
    }

    /**
     * 自提点详情
     *
     * @param Content $content
     * @param int $id
     * @return Content|string
     */
    public function show(Content $content, $id)
    {
        // 如果是Ajax请求，只返回详情内容
        if (request()->ajax()) {
            return $this->renderPickupPointDetail($id);
        }
        
        return $content
            ->title('自提点详情')
            ->description('查看自提点详细信息')
            ->body($this->renderPickupPointDetail($id));
    }

    /**
     * 创建自提点
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->title('新增自提点')
            ->description('创建新的自提点')
            ->body($this->renderPickupPointForm());
    }

    /**
     * 编辑自提点
     *
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function edit(Content $content, $id)
    {
        return $content
            ->title('编辑自提点')
            ->description('编辑自提点信息')
            ->body($this->renderPickupPointForm($id));
    }

    /**
     * 渲染自提点列表
     *
     * @param Request $request
     * @return string
     */
    protected function renderPickupPointList(Request $request)
    {
        // 获取通过审核的自提点申请对应的门店
        $query = Store::whereHas('approvedPickupPointApplications');
        
        // 搜索筛选
        if ($request->filled('province')) {
            $query->where('province_id', $request->province);
        }
        
        if ($request->filled('city')) {
            $query->where('city_id', $request->city);
        }
        
        if ($request->filled('district')) {
            $query->where('district_id', $request->district);
        }
        
        if ($request->filled('pickup_name')) {
            $query->where('store_name', 'like', '%' . $request->pickup_name . '%');
        }
        
        if ($request->filled('applicant_id')) {
            $query->whereHas('member', function($q) use ($request) {
                $q->where('uid', $request->applicant_id);
            });
        }
        
        if ($request->filled('member_info')) {
            $query->whereHas('member', function($q) use ($request) {
                $q->where('nickname', 'like', '%' . $request->member_info . '%')
                  ->orWhere('mobile', 'like', '%' . $request->member_info . '%');
            });
        }
        
        // 获取数据并格式化
        $stores = $query->with(['approvedPickupPointApplications' => function($q) {
            $q->latest();
        }, 'member'])->paginate(15);
        

        
        $pickupPoints = [];
        
        foreach ($stores as $store) {
            $latestApplication = $store->approvedPickupPointApplications->first();
            
            if ($latestApplication) {
                $pickupPoints[] = [
                    'id' => $store->id,
                    'name' => $store->store_name,
                    'district' => $this->getDistrictName($store->province_id, $store->city_id, $store->district_id),
                    'applicant' => [
                        'name' => $store->member->nickname ?? '未知联系人',
                        'id' => $store->member->uid ?? '未知ID',
                        'avatar' => $store->member->avatar ?? $this->generateAvatar('未知')
                    ],
                    'phone' => $store->mobile,
                    'status' => $latestApplication->pickup_status_label,
                    'pickup_point_status' => $latestApplication->pickup_point_status,
                    'store' => $store,
                    'application' => $latestApplication
                ];
            }
        }
        
        return view('admin.pickup.index', compact('pickupPoints', 'stores'));
    }

    /**
     * 渲染自提点详情
     *
     * @param int $id
     * @return string
     */
    protected function renderPickupPointDetail($id)
    {
        try {
            $store = Store::with(['approvedPickupPointApplications' => function($q) {
                $q->latest();
            }, 'member'])->find($id);

            if (!$store) {
                return '<div class="text-center py-5"><p class="text-danger">门店不存在</p></div>';
            }

            $latestApplication = $store->approvedPickupPointApplications->first();

            if (!$latestApplication) {
                return '<div class="text-center py-5"><p class="text-danger">该门店没有通过审核的自提点申请</p></div>';
            }

            $pickupPoint = [
                'id' => $store->id,
                'name' => $store->store_name ?? '未知门店',
                'category' => $this->getCategoryName($store->category_id ?? 0),
                'business_status' => $store->operating_state == 1 ? 'normal' : 'suspended',
                'province' => $this->getProvinceName($store->province_id),
                'province_id' => $store->province_id,
                'city' => $this->getCityName($store->city_id),
                'city_id' => $store->city_id,
                'district' => $this->getDistrictName($store->province_id, $store->city_id, $store->district_id),
                'district_id' => $store->district_id,
                'detailed_address' => $store->address ?? '',
                'longitude' => $store->longitude ?? '',
                'latitude' => $store->latitude ?? '',
                'contact_phone' => $store->mobile ?? '',
                'store_phone' => $store->mobile ?? '',
                'opening_time' => $store->business_hours_start ?: '08:00',
                'closing_time' => $store->business_hours_end ?: '22:00',
                'establishment_date' => $store->created_at ? $store->created_at->format('Y-m-d\TH:i') : '',
                'manager' => [
                    'name' => $store->username ?: ($store->member->nickname ?? '未设置'),
                    'id' => $store->uid ?? ($store->member->uid ?? ''),
                    'avatar' => ($store->member && $store->member->avatar) ? $store->member->avatar : $this->generateAvatar($store->username ?: $store->store_name)
                ],
                'manager_contact' => $store->mobile ?? '',
                'login_account' => $store->username ?: $store->mobile,
                'business_license' => $this->formatImageUrl($store->aptitude_imgs ?? null),
                'status' => $store->operating_state == 1 ? '正常' : '停用',
                'created_at' => $store->created_at,
                'updated_at' => $store->updated_at,
                'store' => $store,
                'application' => $latestApplication
            ];

            return view('admin.pickup.detail', compact('pickupPoint'))->render();
        } catch (\Exception $e) {
            \Log::error('自提点详情加载失败', [
                'store_id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return '<div class="text-center py-5">
                <i class="fa fa-exclamation-triangle fa-2x text-danger"></i>
                <p class="text-danger mt-3">加载失败: ' . htmlspecialchars($e->getMessage()) . '</p>
                <p class="text-muted">请检查日志获取详细信息</p>
            </div>';
        }
    }

    /**
     * 渲染自提点表单
     *
     * @param int|null $id
     * @return string
     */
    protected function renderPickupPointForm($id = null)
    {
        $pickupPoint = $id ? [
            'id' => $id,
            'name' => '北京朝阳自提点',
            'address' => '北京市朝阳区建国路88号',
            'contact' => '张三',
            'phone' => '13800138001',
            'email' => 'zhangsan@example.com',
            'status' => '正常',
            'business_hours' => '9:00-18:00',
            'description' => '位于商业区核心地带，交通便利。'
        ] : null;

        return view('admin.pickup.form', compact('pickupPoint'));
    }

    /**
     * 生成头像SVG
     *
     * @param string $name
     * @return string
     */
    private function generateAvatar($name)
    {
        $colors = ['#FFC537', '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8'];
        $color = $colors[array_rand($colors)];
        $initials = mb_substr($name, 0, 1, 'UTF-8');
        
        return "data:image/svg+xml;base64," . base64_encode("
            <svg width='32' height='32' viewBox='0 0 32 32' fill='none' xmlns='http://www.w3.org/2000/svg'>
                <circle cx='16' cy='16' r='16' fill='{$color}'/>
                <text x='16' y='20' font-family='Arial, sans-serif' font-size='14' font-weight='bold' text-anchor='middle' fill='white'>{$initials}</text>
            </svg>
        ");
    }

    /**
     * 获取地区名称
     *
     * @param int $provinceId
     * @param int $cityId
     * @param int $districtId
     * @return string
     */
    private function getDistrictName($provinceId, $cityId, $districtId)
    {
        try {
            // 从数据库获取真实的地址信息
            $province = Address::find($provinceId);
            $city = Address::find($cityId);
            $district = Address::find($districtId);
            
            $provinceName = $province ? $province->areaname : '未知省份';
            $cityName = $city ? $city->areaname : '未知城市';
            $districtName = $district ? $district->areaname : '未知区县';
            
            return "{$provinceName}{$cityName}{$districtName}";
        } catch (\Exception $e) {
            // 如果数据库查询失败，返回默认格式
            return "省市区信息获取失败";
        }
    }

    /**
     * 获取分类名称
     *
     * @param int $categoryId
     * @return string
     */
    private function getCategoryName($categoryId)
    {
        $categories = [
            1 => '餐饮',
            2 => '零售',
            3 => '服务',
            4 => '其他'
        ];
        
        return $categories[$categoryId] ?? '未分类';
    }

    /**
     * 获取省份名称
     *
     * @param int $provinceId
     * @return string
     */
    private function getProvinceName($provinceId)
    {
        try {
            $province = Address::find($provinceId);
            return $province ? $province->areaname : '未知省份';
        } catch (\Exception $e) {
            return '未知省份';
        }
    }

    /**
     * 获取城市名称
     *
     * @param int $cityId
     * @return string
     */
    private function getCityName($cityId)
    {
        try {
            $city = Address::find($cityId);
            return $city ? $city->areaname : '未知城市';
        } catch (\Exception $e) {
            return '未知城市';
        }
    }

    /**
     * 格式化图片URL
     *
     * @param string|array|null $imageUrl
     * @return string
     */
    private function formatImageUrl($imageUrl)
    {
        if (empty($imageUrl)) {
            return '未提供';
        }

        // 如果是数组,取第一个元素
        if (is_array($imageUrl)) {
            $imageUrl = reset($imageUrl);
            if (empty($imageUrl)) {
                return '未提供';
            }
        }

        // 确保是字符串
        $imageUrl = (string) $imageUrl;

        // 如果已经是完整的URL，直接返回
        if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
            return $imageUrl;
        }

        // 如果是相对路径，添加域名前缀
        if (strpos($imageUrl, '/') === 0) {
            return request()->getSchemeAndHttpHost() . $imageUrl;
        }

        // 如果是文件名，假设存储在public目录下
        return request()->getSchemeAndHttpHost() . '/storage/' . $imageUrl;
    }

    /**
     * 切换自提点状态
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function toggleStatus(Request $request): JsonResponse
    {
        try {
            $storeId = $request->get('store_id');
            $newStatus = $request->get('pickup_point_status');
            
            if (!$storeId || !in_array($newStatus, ['allow', 'deny'])) {
                return response()->json([
                    'status' => 'error',
                    'message' => '参数不完整或无效'
                ], 400);
            }
            
            // 查找门店对应的最新申请记录
            $store = Store::with(['approvedPickupPointApplications' => function($q) {
                $q->latest();
            }])->find($storeId);
            
            if (!$store) {
                return response()->json([
                    'status' => 'error',
                    'message' => '门店不存在'
                ], 404);
            }
            
            $application = $store->approvedPickupPointApplications->first();
            if (!$application) {
                return response()->json([
                    'status' => 'error',
                    'message' => '该门店没有通过审核的自提点申请'
                ], 404);
            }
            
            // 更新自提点状态
            $application->pickup_point_status = $newStatus;
            $application->save();
            
            $statusText = $newStatus === 'allow' ? '启用' : '停用';
            
            return response()->json([
                'status' => 'success',
                'message' => "自提点状态已成功切换为：{$statusText}",
                'data' => [
                    'store_id' => $storeId,
                    'pickup_point_status' => $newStatus,
                    'status_label' => PickupPointApplication::$pickupStatusLabels[$newStatus]
                ]
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '状态切换失败：' . $e->getMessage()
            ], 500);
        }
    }
}